/*****************************************************************************/
function FormEditor(rootDiv,settings,formdata)
{
	this.formdata=formdata;
	eval('this.config='+formdata.config);
	this.settings=settings;
	this.divs={};
	this.divs.root=rootDiv;
	this.init();
}

/*****************************************************************************/
FormEditor.prototype.init=function() {
	var t=this;
	this.form=this.divs.root.ajajform({
		header: "Редактирование формы",
		layouttemplate: "<table class='formeditor'><tr class='formeditor'><td class='visual'></td><td class='right'><div class='new-widgets'><h2>Доступные элементы</h2><div style='clear: both;'></div></div><div class='settings'><h2>Настройки</h2></div></td></tr></table>",
		submit: {
			url: '/admin-forms/',
			ajaj: true,
			params: {mode: 'save',ajaj:1,id:this.formdata.id},
			value: "Сохранить",
			click: function(r,r2) {
				for (var k in r) {
					if (k.match(/^i-/)) t.config[k.replace(/^i-/,'')]=r[k];
				}
				t.config.saved_message=r.saved_message;
				r.config=jQuery.toJSON(t.config);
				return true;
			}
		},
		footerButtons: [
			{ value: "Test",click: function() { t.divs.debug.text(Dumper(t.config).replace(/\t/g,' '));}},
			{ value: "Refresh",click: function() { t.init_visual();}}
		]
	});
	this.init_settings();
	this.init_new_widgets();
	this.set_style(this.config.style_id);
	this.init_visual();
	this.divs.debug=$('<pre style="overflow: auto; width: 380px; max-height: 400px;" class="debug"></pre>').appendTo($(".settings",this.divs.root));
}

/*****************************************************************************/
FormEditor.prototype.init_settings=function() {
	var t=this;
	this.form.ajajform("insertWidget",'.settings',null,{
		type: "textedit",
		name: "code",
		label: "Form code-name",
		width: 220,
		validate: function(x) {if (!x || x=="" || x=="0") return "Пустое название";},
		value: this.formdata.code
	});
	this.form.ajajform("insertWidget",'.settings',null,{
		type: "textedit",
		name: "name",
		label: "Название формы",
		validate: function(x) {if (!x || x=="" || x=="0") return "Пустое название";},
//		change: function() {call_page_editor_rebuild_blocks();},
		width: 220,
		value: this.formdata.name
	});
	this.form.ajajform("insertWidget",'.settings',null,{
		type: "textedit",
		name: "header",
		label: "Заголовок формы",
		width: 220,
		value: this.formdata.header
	});
	this.form.ajajform("insertWidget",'.settings',null,{
		type: "select",
		name: "style_id",
		label: "Стиль",
		values: this.settings.form_styles,
		validate: function(x) {if (!x || x=="" || x=="0") return "Не выбран стиль формы";},
		change: function(x) {
			var sel=x.data.tag;
			t.set_style(sel.val());
		},
		width: 220,
		value: this.config.style_id
	});
	this.form.ajajform("insertWidget",'.settings',null,{
		type: "textedit",
		name: "i-action",
		label: "URL перехода",
		width: 220,
		value: this.config.action
	});
	this.form.ajajform("insertWidget",'.settings',null,{
		type: "textedit",
		name: "i-submit_value",
		label: "Текст кнопки \"сохранить\"",
		width: 220,
		value: this.config.submit_value
	});
/*
	this.form.ajajform("insertWidget",'.settings',null,{
		type: "textareaedit",
		name: "saved_message",
		label: "Сообщение об успешном сохранении",
		width: 420,
		height: 200,
		wysiwyg: true,
		value: this.config.saved_message
	});
*/
}

/*****************************************************************************/
FormEditor.prototype.init_new_widgets=function()
{
	var widgets=["checkbox","date","fileupload","grid","label","select","textareaedit","textedit"];
	var nwblock1=$(".new-widgets",this.divs.root);
	var nwblock2=$(".new-widgets div",this.divs.root);
	var t=this;
	for (var i=0;i<widgets.length;i++) {
		var wname=widgets[i];
		$("<input type='button' class='new-widget ui-corner-all'/>").insertBefore(nwblock2).attr("value",wname).bind("click",{t:t,widget:wname},function(e) {e.data.t.add_widget_clicked(e.data.widget);});
	}
}

/*****************************************************************************/
FormEditor.prototype.set_style=function(style_id)
{
	if (style_id!=this.config.style_id) {
		this.config.style_id=style_id;
	}
	if (style_id==null || style_id==undefined || style_id=="") {
		$(".visual",this.divs.root).empty();
		return;
	}
	this.style=undefined;
	for (var i=0;i<this.settings.form_styles.length;i++) {
		var st=this.settings.form_styles[i];
		if (st.id==style_id) this.style=st;
	}
	if (!this.style) alert("Стиль не найден");
	$(".visual",this.divs.root).empty();
	var html=this.style.editor_body?this.style.editor_body:this.style.real_body;
	$(".visual",this.divs.root).html(html);
	var arr=this.style.places.split(/ /);
	for (var i=0;i<arr.length;i++) {
		$(".visual "+arr[i]).addClass("widgetholder");
		$(".visual "+arr[i]).attr("id","place-id-"+i);
	}
}

/*****************************************************************************/
FormEditor.prototype.add_widget_clicked=function(widget_name)
{
	if (!this.style) return;
	var i=this.config.widgets.length;
	var arr=this.style.places.split(/ /);
	var h={
		place: arr[0],
		options: {
			type: widget_name,
			name: "new"+i,
			label: "New widget "+i,
			width: 200,
			value: ""
		}
	};
	this.config.widgets.push(h);
	this.widget_draw(this.config.widgets.length-1);
	//this.form.ajajform("insertWidget",'.settings',null,{});
}

/*****************************************************************************/
FormEditor.prototype.gen_dialogid=function()
{
	var i=1;
	while (document.getElementById("dialogid"+i)) i++;
	return "dialogid"+i;
}

/*****************************************************************************/
FormEditor.prototype.del_widget_clicked=function(widget_id)
{
	var t=this;
	var w=this.config.widgets[widget_id];
	var dialogid=this.gen_dialogid();
	var html="<div id='"+dialogid+"' class='widget-del-dialog'></div>";
	$(html).appendTo($("body"));
	var d=$("#"+dialogid);
	d.dialog({
		title: "Удаление элемента формы",
		height:190,
		modal: true,
		buttons: [
			{text: "Удалить",click: function() {t.del_widget(widget_id);d.dialog("close");}},
			{text: "Отмена", click: function() {d.dialog("close");}}
		],
		close: function() { d.dialog("destroy");d.remove(); }
	});
	d.html("<div class='msg1'>Удалить элемент формы '"+w.options.name+"'?</div><div class='img'><img src='/shared/adminpanel/formeditor/mockup_"+w.options.type+".png'/></div>");
}

/*****************************************************************************/
FormEditor.prototype.del_widget=function(widget_id)
{
	this.config.widgets.splice(widget_id,1);
	this.init_visual();
}

/*****************************************************************************/
FormEditor.prototype.edit_object_mkinput=function(type,div,p,value,widget_id,widget_obj)
{
	var t=this;
	div.empty();
	switch (type) {
		case "":
			break;
		case "string":
		case "integer":
		case "html":
			$("<input type='text' class='max value save' name='val-"+p.name+"' value=''/>").appendTo(div).attr("value",value);
			break;
		case "boolean":
			$("<input type='checkbox' class='save' name='val-"+p.name+"' value='1'/>").appendTo(div).attr("checked",value);
			break;
		case "array":
			var a=$("<input type='button' class='max value ui-corner-all' value='[ Массив, "+value.length+" элементов ]'/>");
			a.appendTo(div);
			a.bind("click",{t:t,value:value,p:p},function(e) {
				e.data.t.dialog_edit_object(e.data.value,e.data.p,0,widget_id,widget_obj);
			});
			break;
		case "object":
			var cnt=0;
			var a=$("<input type='button' class='max value ui-corner-all' value='[ Объект, "+cnt+" свойств ]'/>");
			a.appendTo(div);
			a.bind("click",{t:t,value:value,p:p},function(e) {
				e.data.t.dialog_edit_object(e.data.value,e.data.p,0,widget_id,widget_obj);
			});
			break;
		case "compile":
			$("<input type='text' class='max value save compile' name='val-"+p.name+"' value=''/>").appendTo(div).attr("value",value);
			break;
		default:
			div.html("<b><i>Неизвестный тип "+type+"</i></b>");
			break;
	}
}

/*****************************************************************************/
FormEditor.prototype.dialog_edit_object=function(obj,settings,do_reload_on_close,widget_id,widget_obj)
{
	var t=this;
	var d=$("<div class='object-edit-dialog' title='Редактирование свойств объекта "+widget_obj.options.name+"/"+widget_obj.options.type+"'><div class='img'><img src='/shared/adminpanel/formeditor/mockup_"+widget_obj.options.type+".png'/></div><div class='items'></div></div>").appendTo($("body"));
	var buttons=[];
	var items_div=$(".items",d);
	switch (settings.type) {
		case "array":
			var p=settings.items;
			for (var i=0;i<obj.length;i++) {
				var item_div=$("<div class='item'><div class='name'>Элемент "+i+"</div><div class='set'><input type='checkbox' class='set' name='del-"+p.name+"' value='1'/></div><div class='value'></div><div style='clear: both;'></div></div>").appendTo(items_div);
				this.edit_object_mkinput(p.type,$(".value",item_div),p,obj[i],widget_id,widget_obj);
			}
			buttons.push({text: "Добавить",click: function() {
				obj.push(Clone(p["default-value"]));
				var i=obj.length-1;
				var item_div=$("<div class='item'><div class='name'>Элемент "+i+"</div><div class='set'><input type='checkbox' class='set' name='del-"+p.name+"' value='1'/></div><div class='value'></div><div style='clear: both;'></div></div>").appendTo(items_div);
				t.edit_object_mkinput(p.type,$(".value",item_div),p,obj[i],widget_id,widget_obj);
			}});
			buttons.push({text: "Удалить выбранные",click: function() {
			}});
			break;
		case "object":
			for (var i=0;i<settings.properties.length;i++) {
				var p=settings.properties[i];
				var item_div=$("<div class='item'><div class='name'>"+p.name+"</div><div class='set'><input type='radio' name='set-"+p.name+"' value='0'/><input type='radio' name='set-"+p.name+"' value='1'/><input type='radio' name='set-"+p.name+"' value='2'/></div><div class='value'></div><div style='clear: both;'></div></div>").appendTo(items_div);
				$(".set input",item_div).bind("change",{t:t,p:p,item_div:item_div,obj:obj},function(e) {
					var p=e.data.p;
					var val=1*$(this).attr("value");
					var type;//=p.type;
					switch (val) {
						case 1:
							if (!(p.name in e.data.obj)) e.data.obj[p.name]=Clone(p["default-value"]);
							type=p.type;
							break;
						case 2:
							type="compile";
							break;
						case 0:
							type="";
							delete e.data.obj[p.name];
							break;
						default:
							alert("unknown .set value="+val);
					}
					e.data.t.edit_object_mkinput(type,$(".value",e.data.item_div),p,e.data.obj[p.name],widget_id,widget_obj);
				});
				if (p.name in obj) {
					var compile=0;
					if (typeof(obj[p.name])=="string" && obj[p.name].match(/^(function|\{\{)/)) compile=1;
					$(".set input[value="+(compile+1)+"]",item_div).attr("checked",true);
					this.edit_object_mkinput(compile==1?"compile":p.type,$(".value",item_div),p,obj[p.name],widget_id,widget_obj);
				} else {
					$(".set input[value=0]",item_div).attr("checked",true);
				}
			}
			break;
		default:
			alert("Unknown object type!\n");
			return;
	}
	buttons.push({text: "Сохранить",click: function() {
		if (settings.type=="object") {
			for (var i=0;i<settings.properties.length;i++) {
				var p=settings.properties[i];
				var inp=$('.value input[name="val-'+p.name+'"]',items_div);
				if (inp.length==0) continue;
				var type=p.type;
				if (inp.hasClass("compile")) type="compile";
				switch (type) {
					case "html":
					case "string":
						obj[p.name]=inp.attr("value");
						break;
					case "integer":
						obj[p.name]=inp.attr("value")==""?null:1*inp.attr("value");
						break;
					case "boolean":
						obj[p.name]=inp.attr("checked")?true:false;
						break;
					case "compile":
						obj[p.name]=inp.attr("value");
						break;
					default:
						alert("Unknown property save - "+p.type);
				}
			}
		}
		if (do_reload_on_close) t.widget_draw(widget_id);
		d.dialog("close");
	}});
	if (settings.type=="object") buttons.push({text: "Отмена", click: function() {d.dialog("close");}});
	d.dialog({
		height:500,
		width: 500,
		modal: true,
		buttons: buttons,
		close: function() { d.dialog("destroy");d.remove(); }
	});
}

/*****************************************************************************/
FormEditor.prototype.edit_widget_clicked=function(widget_id)
{
	var w=this.config.widgets[widget_id];
	var wsettings=this.widget_settings(w.options.type);
	if (!wsettings) {
		alert("wsettings==null, w.options.type="+w.options.type);
		return;
	}
	this.dialog_edit_object(w.options,wsettings,true,widget_id,w);
	this.widget_draw(widget_id);
}

/*****************************************************************************/
FormEditor.prototype.init_visual=function()
{
	var t=this;
	$(".visual .widgetholder",this.divs.root).empty();
	for (var i=0;i<this.config.widgets.length;i++) {
		this.widget_draw(i);
	}
	if (this.sortable_inited) return;
	this.sortable_inited=true;
	$(".visual .widgetholder").sortable({
		connectWith: ".widgetholder ",
		handle: "span",
		stop: function(event,ui) {
			var oldw=t.config.widgets;
			var neww=t.config.widgets=[];
			var sortables=$(".visual .widgetholder");
			var s=0;
			var places=t.style.places.split(/ /);
			for (var j=0;j<sortables.length;j++) {
				var arr=$(sortables[j]).sortable('toArray');
				var place_id=$(sortables[j]).attr("id").replace(/^place-id-/,'');
				var place=places[place_id];
//				alert('j='+j+', arr='+arr.join(','));
				for (var i=0;i<arr.length;i++) {
					neww[s]=oldw[arr[i].replace(/\D+/g,'')];
					neww[s].place=place;
					s++;
				}
			}
			t.init_visual();
		}
	});
}

/*****************************************************************************/
FormEditor.prototype.widget_draw=function(i)
{
	var t=this;
	var h=this.config.widgets[i];
	var wdiv=$(".visual #w-"+i,this.divs.root);
	if (!wdiv.length) {
		wdiv=$("<div class='widget-mockup ui-corner-all' id='w-"+i+"'><span class='sort'></span><div class='textblock'><div class='label'></div><div class='name'></div></div><div class='mockup'><img src='/shared/empty.gif'/></div><div class='controls'></div><div style='clear: both;'></div></div>").appendTo($(".visual "+h.place,this.divs.root));
		$("<img src='/shared/icons/edit.png'/>").appendTo($(".controls",wdiv)).bind("click",{t:t,i:i},function(e) {e.data.t.edit_widget_clicked(e.data.i);});
		$("<img src='/shared/icons/delete.png'/>").appendTo($(".controls",wdiv)).bind("click",{t:t,i:i},function(e) {e.data.t.del_widget_clicked(e.data.i);});
	}
	$(".label",wdiv).text(h.options.label);
	$(".name",wdiv).text(h.options.name);
	$(".mockup img",wdiv).attr("src","/shared/adminpanel/formeditor/mockup_"+h.options.type+".png");
}

/*****************************************************************************/
FormEditor.prototype.widget_settings=function(name)
{
	var arr=[
		{name: "name", type: "string","default-value":""},
		{name: "cssclass", type: "string","default-value":"afw-"+name},
		{name: "label", type: "string"}
	];
	var ret={
		type: "object",
		properties: arr
	};
	switch(name) {
		case "checkbox":
			return ret;
		case "date":
			return ret;
		case "fileupload":
			return ret;
		case "grid":
			return ret;
		case "label":
			arr.push({name: "value", type: "string", "default-value": ""});
			arr.push({name: "htmltemplate", type: "html", "default-value": ""});
			arr.push({name: "html", type: "boolean", "default-value": false});
			arr.push({name: "width", type: "integer", "default-value": 400});
			return ret;
		case "select":
			arr.push({name: "value", type: "string", "default-value": ""});
			arr.push({name: "htmltemplate", type: "html", "default-value": ""});
			arr.push({name: "htmltemplate_disableable", type: "html", "default-value": ""});
			arr.push({name: "width", type: "integer", "default-value": 400});
			arr.push({
				name: "values",
				type: "array",
				"default-value": [],
				items: {
					type: "object",
					properties: [
						{name: "id", type: "string", "default-value": ""},
						{name: "name", type: "string", "default-value": ""}
					],
					"default-value": {id:"",name:""}
				}
			});
			arr.push({name: "disabled", type: "boolean", "default-value": false});
			arr.push({name: "disableable", type: "boolean", "default-value": false});
			return ret;
		case "textareaedit":
			arr.push({name: "value", type: "string", "default-value": ""});
			arr.push({name: "htmltemplate", type: "html", "default-value": ""});
			arr.push({name: "htmltemplate_disableable", type: "html", "default-value": ""});
			arr.push({name: "width", type: "integer", "default-value": 400});
			arr.push({name: "height", type: "integer", "default-value": 200});
			arr.push({name: "wysiwyg", type: "boolean", "default-value": false});
			arr.push({name: "wysiwyg_toolbar", type: "enum", "default-value": "external",values: ["external","top","bottom"]});
			arr.push({name: "disabled", type: "boolean", "default-value": false});
			arr.push({name: "disableable", type: "boolean", "default-value": false});
			return ret;
		case "textedit":
			arr.push({name: "value", type: "string", "default-value": ""});
			arr.push({name: "htmltemplate", type: "html", "default-value": ""});
			arr.push({name: "htmltemplate_disableable", type: "html", "default-value": ""});
			arr.push({name: "password", type: "boolean", "default-value": false});
			arr.push({name: "width", type: "integer", "default-value": null});
			arr.push({name: "autocomplete", type: "any", "default-value": null});
			arr.push({name: "validate", type: "function", "default-value": null});
			arr.push({name: "change", type: "function", "default-value": ""});
			arr.push({name: "disabled", type: "boolean", "default-value": false});
			arr.push({name: "disableable", type: "boolean", "default-value": false});
			return ret;
	}
}

/*****************************************************************************/
